import React from 'react';
import { Modal, Row, Col, Select, message, Button, Collapse } from 'antd';
import Editor from '@/utils/Editor';
import JsonAnswer from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/jsonAnswer';
import jsonDataUtils from '@/utils/jsonDataUtils';
import UserSession from "@/UserSession";

class EditAnswer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      robotName: '',
      robotId: '',
      slotValues: [],
      userTagIdList: [],
      answer: { isDefault: true, content: '' }
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  initModal = (objItem) => {
    //用于处理子组件改变了值 导致父组件的值也被改变
    let obj = JSON.parse(JSON.stringify(objItem));
    this.setState({
      visible: true,
      robotName: obj.robotName,
      robotId: obj.activeKey,
      answerIndex: obj.answerIndex,
      answer: obj.answer,
      slotValues: obj.answer.slotValues ? obj.answer.slotValues : [],
      userTagIdList: obj.answer.userTagIdList ? obj.answer.userTagIdList : [],
    })
  }

  cancelModal = () => {
    this.setState({
      visible: false,
      robotName: '',
      robotId: '',
      slotValues: [],
      userTagIdList: [],
    })
  }

  /**
   * 选择词槽
   * @returns {*}
   */
  changeSlot = (values, id, slotName, keyName) => {
    let { slotValues } = this.state;
    //判断当前词槽是否选择过 没有则添加 有则修改
    const slotIds = slotValues.map(item => item.id);
    if (slotIds.indexOf(id) === -1) {
      slotValues.push({ id, slotName, keyName, values });
    } else {
      if (values.length === 0) {//词槽值全部删除，则去掉该词槽
        const newSlotValues = slotValues.filter(slot => slot.id != id);
        slotValues = newSlotValues;
      } else {
        for (let item of slotValues) {
          if (item.id === id) {
            item.values = values;
          }
        }
      }
    };
    this.setState({ slotValues });
  }

  /**
   * 选择标签
   */
  changeTag = (e, option) => {
    let userTagIdList = option.map(tag => {
      let item = tag.props.item;
      return { id: item.id, tagName: item.tagName };
    });
    this.setState({ userTagIdList });
  }

  /**
   * 选择引用答案
   * @param row
   */
  changeAnswerByRefer = (row) => {
    let { answer } = this.state;
    answer.isRefer = true;
    // answer.referInfo = row;
    answer.content = row.answer;
    answer.contentId = row.id;
    answer.question = row.question;
    /* 若之前的答案类型为json 则引用答案之后需要将类型修改为富文本 防止取消引用后保存content会被jsonContent覆盖 */
    answer.answerType = 'richText';
    this.setState({ answer });
  }

  /**
   * 取消引用
   */
  changeAnswerDereference = () => {
    let { answer } = this.state;
    answer.isRefer = false;
    answer.contentId = undefined;
    answer.question = undefined;
    // answer.referInfo = {};
    this.setState({ answer });
  }

  /**
   * 保存答案
   * @returns {*}
   */
  saveAnswer = () => {
    const { slotValues, userTagIdList, robotId, answer, answerIndex } = this.state;
    const { slotDetailArr } = this.props;
    const con = `answer`;
    // console.log(answer);
    if (!answer.isRefer && !(answer.contentId && answer.question)) {
      let content = '';
      if (con && this.refs[con]) {
        content = this.refs[con].getUeditorContent();
      } else {
        content = '';
      };
      answer.content = content;
    };
    answer.slotValues = slotValues;
    answer.userTagIdList = userTagIdList;
    if (slotDetailArr && slotDetailArr.length > 0) {
      let arr = slotDetailArr.filter(item => item.isEnum);
      let arrSlot = arr.map(item => item.id);
      let slotValuesCheck = !slotValues || slotValues.length === 0 ? [] : slotValues.filter(item => item.values.length > 0);
      if (arr.length > 0 && (!answer.isDefault && (slotValues && slotValues.length > 0 && slotValuesCheck.length < slotValues.length))) {
        message.error('词槽答案词槽值不能为空，请选择词槽');
        return false;
      };
    } else {
      if (!UserSession.isAdmin() && ((!userTagIdList && !answer.isDefault) || (userTagIdList.length === 0 && !answer.isDefault))) {
        message.error('用户标签不能为空，请选择标签')
        return false;
      }
    };
    if (answer.answerType && answer.answerType === 'json' && !jsonDataUtils.judgeJson(answer.jsonContent).flag) {
      message.error(jsonDataUtils.judgeJson(answer.jsonContent).msg);
      return false
    };
    if (answer.answerType && answer.answerType === 'json' && jsonDataUtils.judgeJson(answer.jsonContent).flag) {
      answer.content = JSON.stringify(answer.jsonContent);
      answer.jsonResult = jsonDataUtils.judgeJson(answer.jsonContent);
    };
    if (!answer.content) {
      message.error('请添加答案');
      return false;
    };
    // console.log(answer);
    this.props.editSlotAnswer(answer, robotId, answerIndex);
    this.cancelModal();
  }

  /* 设置答案为json */
  toJsonEditAnswer = () => {
    // 1.获取当前编辑框内的富文本内容，保存至content中，为了json编辑时返回富文本编辑后还能显示之前的内容
    // 2.修改当前答案的类型为json
    // 3.判断是否有保留的json，有则显示保留的json，无则赋值初始json
    let { answer } = this.state;
    const content = this.refs['answer'].getUeditorContent();
    answer.content = content;
    answer.answerType = 'json';
    if (!answer.jsonContent) {
      answer.jsonContent = JSON.parse(JSON.stringify(jsonDataUtils.initJsonData));
    };
    this.setState({ answer });
  }

  /* 更新json答案 */
  updateJsonAnswer = (option, data) => {
    let { answer } = this.state;
    switch (option) {
      case 'backToRich':
        answer.answerType = 'richText';
        break;
      case 'update':
        answer.jsonContent = data;
        break;
    };
    this.setState({ answer });
  }

  render() {
    const { visible, robotName, answer } = this.state;

    const { slotDetailArr, userTagList, tagEditValues } = this.props;
    const getDefaultValue = slotId => {
      let defaultValue = [];
      for (const item of answer.slotValues) {
        if (item.id === slotId) {
          defaultValue = item.values;
        }
      };
      return defaultValue;
    };
    const getTagValue = values => {
      if (values && values.length > 0) {
        let defaultValue = values.map(tag => tag.id);
        return defaultValue;
      } else {
        return [];
      }
    };
    const referAnswerHeader = referQuestion => (
      <span>引用自答案库：<a>{referQuestion}</a></span>
    );
    const referAnswerExtra = UserSession.isSystemKnowledge() ? null : (
      <span>
        <span style={{ marginRight: 5, color: '#11cbff' }} onClick={() => this.props.openReferAnswer('slotEdit')}>更换</span>
        <span style={{ color: '#11cbff' }} onClick={this.changeAnswerDereference}>取消引用</span>
      </span>
    );

    return (
      <Modal
        visible={visible}
        title={'添加/编辑答案'}
        onCancel={this.cancelModal}
        width={800}
        onOk={this.saveAnswer}
        destroyOnClose
      >
        <Row>
          <Col span={3}>适用于：</Col>
          <Col span={20}>{robotName}</Col>
        </Row>
        {
          answer.isDefault ? '' : (
            <>
              {slotDetailArr && slotDetailArr.length > 0 ? (
                <Row style={{ marginTop: 10 }}>
                  <Col span={3}>词槽条件：</Col>
                  <Col span={20}>
                    {
                      slotDetailArr.map((slot, index) => {
                        return (
                          <Row key={index} style={{ marginTop: index === 0 ? 0 : 10 }}>
                            <Col span={4}>
                              &lt;{slot.name}&gt; =
                            </Col>
                            <Col span={20}>
                              {
                                slot.isEnum ? (
                                  <Select
                                    mode="multiple"
                                    style={{ width: '100%' }}
                                    defaultValue={getDefaultValue(slot.id)}
                                    onChange={(values) => this.changeSlot(values, slot.id, slot.name, slot.keyName)}
                                  >
                                    {
                                      slot.items.map((item, itemIndex) => {
                                        return (
                                          <Select.Option value={item.word} key={item.id}>{item.word}</Select.Option>
                                        )
                                      })
                                    }
                                  </Select>
                                ) : '词槽值不可枚举，不支持设置条件'
                              }
                            </Col>
                          </Row>
                        )
                      })
                    }
                  </Col>
                </Row>
              ) : null}
              {!UserSession.isAdmin() ? (
                <Row style={{ marginTop: 10 }}>
                  <Col span={3}></Col>
                  <Col span={20}>
                    <Row style={{ marginTop: 10 }}>
                      <Col span={4}>
                        &lt;{'用户标签'}&gt; =
                      </Col>
                      <Col span={20}>
                        <Select
                          mode="multiple"
                          style={{ width: '100%' }}
                          defaultValue={getTagValue(tagEditValues)}
                          onChange={this.changeTag}
                        >
                          {
                            userTagList.map((item, itemIndex) => {
                              return (
                                <Select.Option value={item.id} key={item.id} item={item}>{item.tagName}</Select.Option>
                              )
                            })
                          }
                        </Select>
                      </Col>
                    </Row>
                  </Col>
                </Row>
              ) : null}
            </>
          )
        }
        {UserSession.isSystemDataKnowledge() ? null : (
					<>
            {
              !answer.question ? (
                <Row style={{ marginTop: 10 }}>
                  <Col style={{ textAlign: 'right' }}>
                    <Button
                      style={{ backgroundColor: '#E5ECF4' }}
                      onClick={() => this.props.openReferAnswer('slotEdit')}
                    >引用答案</Button>
                  </Col>
                </Row>
              ) : ('')
            }
          </>
				)}
        <Row style={{ marginTop: 10 }}>
          <Col span={3}>答案：</Col>
          <Col span={20}>
            <div>
              {
                answer.question ? (
                  <Collapse expandIconPosition={'right'} defaultActiveKey={answer.id}>
                    <Collapse.Panel header={referAnswerHeader(answer.question)} extra={referAnswerExtra} key={answer.id}>
                      <div dangerouslySetInnerHTML={{ __html: answer.content }} />
                    </Collapse.Panel>
                  </Collapse>
                ) : (
                  answer.answerType && answer.answerType === 'json' ? (
                    <JsonAnswer
                      jsonContent={answer.jsonContent}
                      updateJsonAnswer={this.updateJsonAnswer}
                      typeOfAnswer={'editAnswer'}
                    />
                  ) : (
                    <Editor
                      content={answer.content}
                      name={`answer`}
                      id={`answer`}
                      ref={`answer`}
                      toJson={this.toJsonEditAnswer}
                    />
                  )
                )
              }
            </div>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default EditAnswer;
